﻿using Castle.DynamicProxy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging; //日志ILogger<>
using System.Diagnostics;          //StopWatch所在命名空间
namespace Infrastructure.Common
{

    public class ServiceLoggerInterceptor : IInterceptor
    {
        private readonly ILogger<ServiceLoggerInterceptor> _logger;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="logger"></param>
        public ServiceLoggerInterceptor(ILogger<ServiceLoggerInterceptor>
        logger)
        {
            _logger = logger;
        }
        /// <summary>
        /// 拦截器接口方法
        /// </summary>
        /// <param name="invocation"></param>
        /// <exception cref="NotImplementedException"></exception>
        public void Intercept(IInvocation invocation)
        {
            //执行方法前
            //开始秒表技术
            var sw = new Stopwatch();
            //执行方法
            invocation.Proceed();

            //执行方法后 做点什么
            //结束秒表计时
            sw.Stop();

            //输出日志
            string actionName = invocation.Method.Name;
            string className = invocation.TargetType.Name;
            _logger.LogInformation($"  {className}的{actionName}方法，用时{sw.ElapsedMilliseconds}毫秒\n,执行结果是{invocation.ReturnValue}");
        }
    }
}
